import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      needLogin: false,
      keepAlive: true
    }
  },
  {
    path: '/cate',
    name: 'cate',
    component: () => import('views/Cate'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  },
  {
    path: '/cart',
    name: 'cart',
    component: () => import('views/Cart'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  },
  {
    path: '/mine',
    name: 'mine',
    component: () => import('views/Mine'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  },
  {
    path: '/detail/:itemId',
    name: 'detail',
    component: () => import('views/Detail'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  },
  {
    path: '/itemList',
    name: 'detail',
    component: () => import('views/ItemList'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('views/Login'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  },
  {
    path: '/order',
    name: 'order',
    component: () => import('views/Order'),
    meta: {
      needLogin: true,
      keepAlive: false
    }
  },
  {
    path: '/contactList',
    name: 'contactList',
    component: () => import('views/ContactList'),
    meta: {
      needLogin: true,
      keepAlive: false
    }
  },
  {
    path: '/contactAdd',
    name: 'contactAdd',
    component: () => import('views/ContactAdd'),
    meta: {
      needLogin: true,
      keepAlive: false
    }
  },
  {
    path: '/contactEdit/:index',
    name: 'contactEdit',
    component: () => import('views/ContactEdit'),
    meta: {
      needLogin: true,
      keepAlive: false
    }
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('views/Search'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  },
  {
    path: '/searchResult',
    name: 'searchResult',
    component: () => import('views/SearchResult'),
    meta: {
      needLogin: false,
      keepAlive: false
    }
  }
]



const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  if (to.fullPath === '/login' || to.fullPath === '/register') {
    next();
  } else {
    if( to.meta.needLogin ) {
      // 需要登录
      const access_token = localStorage.getItem('access_token')
      if (access_token) {
        next()
      }else{
        next({
          path: '/login',
          query: {
            from: to.fullPath
          }
        })
      }
    } else {
      next()
    }
  }
})

export default router
